<template>
	<view class="main">
		<view class="content">
			<image  class="logo" src="/static/logo.jpg"></image>
			<text class="text">五菱科技溯源系统</text>
			<view class="text-area">
				<van-cell-group inset class="custom-border">
					<van-field v-model="code" label="序列码" right-icon="scan" placeholder="请输入序列号"
						@click-right-icon="handleIconClick()" />
				</van-cell-group>
			</view>
			<view style="width: 100%;padding: 25px;">
				<van-button @click="getProductList()" :disabled="!this.code" round block type="primary"
					class="select-btn">查 询</van-button>
			</view>
			<view class="product-cell-area" style="text-align: center;" v-if="isShow">
				<view class="van-cell-group--inset ">

					<van-icon name="youzan-shield" size="100px" color="#07c160" />
					<view style="font-size: 36rpx; font-weight: 700; text-align: center;">验证成功</view>
					<view style="color:#777; margin: 10px;">零件为【五菱科技】原厂配件</view>
				</view>
			</view>
			<view class="product-cell-area" v-if="isShow">
				<van-cell-group inset>
					<van-cell value-class="balck_flex_3" size=small title="产品名称：" :value="productList.product_title">
					</van-cell>

					<van-cell title="产品料号：" value-class="balck_flex_3" :value="productList.product_code">
					</van-cell>
					<van-cell>
						<template #title class="cell-area-titles">
							<div class="flex-container">
								<span class="cell-title">产品状态：{{productList.status}}<van-tag
										:type="getStatusType(productList.status)">{{getStatusText(productList.status)}}</van-tag></span>
							</div>
						</template>
					</van-cell>
					<van-cell>
						<template #title class="cell-area-titles">
							<div class="flex-container">
								<span class="cell-title">产品质量：<van-tag
										:type="getStatusType(productList.product_status)">
										{{productList.product_status==1?"优质":"不良"}}
									</van-tag></span>
							</div>
						</template>
					</van-cell>
					<van-cell title="生产工厂：" value-class="balck_flex_3" :value="productList.factory">
					</van-cell>
					<van-cell v-if="this.productList" value-class="balck_flex_3" value="查看更多" is-link @click="codeDetails()">
					</van-cell>
				</van-cell-group>

			</view>
			<view class="vant-button-area" v-if="isShow">
				<!-- <van-button class="select-btn" round type="success" v-if="isShow" @click="codeDetails()" >查看更多</van-button> -->
				<view v-if="productList.status <2 && staff_type <=1 ">

					<van-button class="select-btn" @click="clickFillInTheForm(this.code)" :disabled="!this.code" round
						block type="primary">填写售后</van-button>
					<van-divider />
				</view>
				<view v-if="staff_type > 0">
				
				<!-- {{staff_type}} -->
				<!-- 4 科技，1门店，2经销商，3工厂 -->
				
				<!-- v-if="this.factory_ids.includes(3) || this.factory_ids.includes(2)" -->
				<van-button class="select-btn" v-if="staff_type !=3 && staff_type !=1 && productList.status <2"
					@click="addCirculate(this.code,2)" :disabled="!this.code" round block type="primary">出库</van-button>
					<!-- v-if="this.factory_ids.includes(1) || this.factory_ids.includes(2)" -->
				<van-button class="select-btn" v-if="staff_type !=3 && productList.status <2"
					@click="addCirculate(this.code,1)" :disabled="!this.code" round block type="success">入库</van-button>

				<van-button class="select-btn" @click="codeCirculate()" v-if="staff_type!=3" round block
					type="primary">流通明细</van-button>
					
				<van-button  class="select-btn"  v-if="staff_/type ==3"
					@click="editProductStatus(this.code,'',1)" :disabled="!this.code" round block
					type="primary">标记为【已生产】</van-button>
					
			<!-- 	<van-button  class="select-btn"  v-if="staff_type ==3 && productList.status==1"
					@click="editProductStatus(this.code,'',0)" :disabled="!this.code" round block
					type="warning">标记为【未生产】</van-button> -->
					
				<van-divider />
				<!-- v-if="this.factory_ids.includes(1) || this.factory_ids.includes(2)" -->
				<van-button  class="select-btn" 
					@click="editProductStatus(this.code,2,'')" :disabled="!this.code" round block
					type="danger">标记为【不良】</van-button>
<!-- v-if="this.factory_ids.includes(1) || this.factory_ids.includes(2)" -->
				<van-button  class="select-btn" 
					@click="editProductStatus(this.code,1,'')" :disabled="!this.code" round block
					type="success">标记为【良好】</van-button>
					
					</view>
			</view>
			<view class="bottom-side-otherLogin"  v-if="isWeixin">
				<view @click="getWeChatCode"  v-if="openid ==''">
					<text>微信登录 </text>
					<image  style="width: 18px;height: 18px;align-items: center;" src="https://xuezhifu-resource.oss-cn-hangzhou.aliyuncs.com/newxuefu/mwx/wx.png"></image>
				</view>

				<view @click="bindUser" v-if="openid !=''">
				<van-divider></van-divider>
					<text>绑定员工 </text>
					<van-icon name="scan" />
				</view>
					
					
			</view>
			
			<view class="bottom-side-otherLogin">
				
			</view>
		</view>
		
<!-- 		<van-tabbar v-model="active" v-if="openid !=''">
		  <van-tabbar-item icon="home-o" to="/pages/index/index">首页</van-tabbar-item>
		  <van-tabbar-item icon="friends-o" to="/pages/user/index">我的</van-tabbar-item>
		</van-tabbar> -->


	</view>
</template>

<script>
	import {
		showToast,
		showSuccessToast,
		showFailToast
	} from 'vant';
	import wxjs from "@/utils/wxjsdk.js";
	import axios from 'axios';
	// import ready from '@/utils/jweixin-1.6.0.js'
	export default {
		data() {
			return {
				isShow: false,
				isWeixin: true,
				openid: '',//
				title: '',
				staff_type: 0,//员工类型
				code: '',
				status: '', // 假设状态值为1，您可以根据实际情况进行修改
				active: 0, // 按下的按钮默认状态，也就是默认的页面
				productList: [],
				factory_ids: [],
				userinfo: uni.getStorageSync('userinfo') || {},
				requestCode: '',
			}
		},
		onLoad(opt) {
			console.log('opt',opt)
			if(opt.code != undefined) this.code = opt.code
			uni.hideTabBar();
			this.openid = uni.getStorageSync('openid');
			// this.openid = "o_oruwxrVO-z7hyNW6Z944BhCXbg"// 测试，莫工
			// uni.setStorageSync('openid',this.openid)// 测试
			
			console.log('openid',this.openid)
			if(this.openid != ""){
				this.getUserInfoByOpenid(this.openid)
				uni.showTabBar();
				return
			}
			
			this.isWeixin = this.isWechat();
			if (this.isWeixin) {
				this.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				this.getLocation();
			}
			// 获取当前请求连接上的参数
			let url = window.location.href;
			// 截取url中的参数
			let index = url.indexOf("="); //获取=的位置
			let str = this.getUrlCode('code')
			// 如果没有=，就直接返回
			if (index === -1) {
				setTimeout(() => {
					showToast('请输入或扫码获取产品信息！');
				}, 500);
				return;
			}
		},

		methods: {
			//修改产品质量,状态
			editProductStatus(code,product_status='',status='') {
				axios({
					method: 'post',
					url: 'https://service.wulings.com/api/code/editProductStatus',
					data: {
						"code": code,
						"status": status,
						"product_status": product_status,
					},
					headers: { // J000000638
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}).then((res) => {
					if (res.data.code == 200) {
						console.log("设置成功！", res);
						showSuccessToast('设置成功！');
						this.getProductList()
					} else {
						console.log("设置失败！", res);
						showFailToast('设置失败！');
					}
				}).catch((error) => {
					console.log("设置失败！", res);
					showFailToast('设置失败！');
				});
			},

			

			needToGetOpenId() {
				showToast("请登录获取用户信息。")
			},

			codeCirculate() {
				uni.navigateTo({
					url: '/pages/index/codeCirculate?code='+this.code
				});
			},
			getMyProduct() {
				uni.navigateTo({
					url: '/pages/user/myProduct'
				});
			},

			checkAuth(){
				const userInfo = uni.getStorageSync('userinfo');
				if (userInfo) {
					return true
				}else{
					return false
				}
			},
			/*微信登录相关  start*/
			//方法：用来判断是否是微信内置的浏览器
			isWechat() {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//方法:用来提取code
			getUrlCode(name) {
				// return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
				const url = decodeURIComponent(location.href);
				const regex = new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', 'g');
				let match;
				let latestCode = null;
				while ((match = regex.exec(url)) !== null) {
					const code = match[1].replace(/\+/g, '%20');
					if (code !== '') {
						latestCode = code;
						console.log('latestCode', latestCode);
					}
				}
				return latestCode;
			},
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				let code = this.getUrlCode('code');
				console.log("code", code);
				if (code) {
					this.getOpenidAndUserinfo(code);
				}
			},
			//请求微信接口，用来获取code
			getWeChatCode() {
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				let appid = 'wxe489380fa569e3f3'

				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid +
					"&redirect_uri=" +
					local +
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			},
			// 页面跳转并携带参数
			codeDetails() {
				if (this.code == '') {
					showToast('请先扫码或输入序列号获取产品信息！');
					return;
				} else {
					uni.navigateTo({
						url: '/pages/productDetail/productDetail?productCode=' + this.code
					});
				}
			},
			//把code传递给后台接口，非静默登录
			getOpenidAndUserinfo(code) {
				axios({
						method: 'post',
						url: 'https://wx.wulings.com/wx.php',
						data: {
							"code": code
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(res => {
						// 成功的回调函数
						uni.showTabBar();
						this.openid = res.data.openid
						uni.setStorageSync('openid',this.openid)
						this.wxGetUserInfo(res.data.openid, res.data.access_token)
					})
					.catch(err => {
						// 请求失败时的回调函数
						console.log('获取 openid 失败', err);
						showFailToast('获取 openid 失败');
					});
			},

			getLocation() {
				wxjs.getLocation();
				let latitude = uni.getStorageSync('latitude');
				// console.log('latitude',latitude);
				let longitude = uni.getStorageSync('longitude');
				// console.log('longitude',longitude);
				// 如果没有经纬度信息，则重新获取
				if (!latitude || !longitude) {
					wxjs.getLocation();
				}
			},

			wxGetUserInfo(openid, access_token) {
				// console.log('access_token',access_token);
				return axios({
						method: 'POST',
						url: 'https://wx.wulings.com/wxGetUserInfo.php',
						data: {
							"openid": openid,
							"access_token": access_token
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(res => {
						console.log('res',res);
						
						var data = {
							"nickname": res.data.nickname,
							"headimgurl": res.data.headimgurl,
							"sex": res.data.sex
						}
						this.getUserInfoByOpenid(openid, data) 
							
					})
			},
			
			getUserInfoByOpenid(openid, data={}) {
				//获得或更新
				data.openid = openid
				axios({
						method: 'post',
						url: 'https://service.wulings.com/api/code/getUserInfoByOpenid',
						data: data,
					})
					.then(response => {
						console.log('response', response.data);
						this.wx_user = response.data.wx_user
						this.userinfo = response.data.wx_user
						this.staff_user = response.data.staff_user
						this.staff_type = response.data.staff_user.type
						
						uni.setStorage('userinfo',response.data.wx_user);
						
						// 
						const factoryId = response.data.staff_user.type;
						this.factory_ids.push(factoryId);
						setTimeout(() => {
							// showSuccessToast('登录成功')
							console.log("this.factory_ids", this.factory_ids)
						}, 1000);
					})
			},

			// 解析URL 参数
			getUrlParam(name) {
				let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
					return unescape(r[2]);
				}
				return null;
			},

		

			clickFillInTheForm(code) {
				this.fillInTheForm(code);
			},

			// 获取产品信息
			getProductList() {
				if (this.loginStatus == false) {
					showToast('请先登录验证信息')
				} else {
					let productList = uni.request({
						url: "https://service.wulings.com/api/code/getCodeList",
						method: 'GET', // 请求方法，可选值包括 'GET'、'POST' 等
						data: {
							code: this.code
						}, // 请求参数
						header: {
							'content-type': 'application/json' // 设置请求的 header，根据实际需要设置
						},
						success: res => {
							// console.log("获取到的数据：", res.data);
							this.productList = res.data;
							// console.log("获取到的数据：", res.data.status);
							if (res.data == null) {
								showFailToast('序列号错误或无此产品');
							} else {
								// showSuccessToast('获取成功！');
								this.isShow = true;
							}
						},
						fail: err => {
							// 请求失败时的回调函数
							showFailToast('请求失败，序列号错误或网络出错');
						}
					});
				}
			},


			// 出入库 J000000638
			addCirculate(code,option_type) {
				// console.log("code",code);
				const status = this.status;
				// console.log("status",status);
				var longitude = uni.getStorageSync('longitude');
				var latitude = uni.getStorageSync('latitude');
				var openid = uni.getStorageSync('openid');
				// console.log("longitude",longitude);
				// console.log("openid",openid);
				
				if (this.staff_type ==0){
					showToast('请先登录！');
					return;
				}
				axios({
					method: 'post',
					url: 'https://service.wulings.com/api/code/addCirculate',
					data: {
						"code": this.code,
						"code_id": this.productList.id,
						"staff_id": this.staff_user.id,
						"fac_ids": this.staff_user.fac_ids,
						// "openid": "o_oruwxrVO-z7hyNW6Z944BhCXbg",
						"latitude": uni.getStorageSync('latitude'),
						"longitude": uni.getStorageSync('longitude'),
						"option_type": option_type
					},
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}).then((res) => {
					if (res.data.code == 200) {
						console.log("操作成功！", res);
						showSuccessToast('操作成功！');
						this.getProductList()
						// uni.navigateTo({
						// 	url: '/'
						// });
					} else {
						console.log("操作失败！", res);
						showFailToast('操作失败！'+res.data.message);
					}
				}).catch((error) => {
					console.log("操作失败！", res);
					showFailToast('操作失败！'+res.data.message);
				});
			},

			fillInTheForm(code) {
				uni.navigateTo({
					url: '/pages/productDetail/customerFormInfo/index?productCode=' + code
				});
			},

			getStatusType(status) {
				switch (status) {
					case 0:
						return 'success';
					case 1:
						return 'success';
					case 2:
						return 'default';
					case -1:
						return 'danger';
					default:
						return 'default';
				}
			},

			getStatusText(status) {
				switch (status) {
					case 0:
						return '未使用';
					case 1:
						return '未激活';
					case 2:
						return '已激活';
					case -1:
						return '已删除';
					default:
						return '未使用';
				}
			},

			handleIconClick() {
				wxjs.scanQRCode({
					needResult: 1,
					onlyFromCamera: true,
					scanType: ['qrCode', 'barCode'],
					success: (res) => {
						const code = res.resultStr;
						this.code = code;
						// 直接请求这个 this.code 
						let requestCodeUrlResponse = uni.request({
							url: this.code,
							method: 'GET', // 请求方法，可选值包括 'GET'、'POST' 等
							// data: {url: window.location.href}, // 请求参数
							header: {
								'content-type': 'application/json' // 设置请求的 header，根据实际需要设置
							},
							success: res => {
								// showSuccessToast('扫码成功！');
							},
							fail: err => {
								// 请求失败时的回调函数
								showFailToast('请求失败');
							}
						});
					},
					fail: (err) => {
						// console.log('err', err);
						showFailToast('扫码失败,参数异常');
					}
				});
			},
			bindUser() {
				wxjs.scanQRCode({
					needResult: 1,
					onlyFromCamera: true,
					scanType: ['qrCode', 'barCode'],
					success: (res) => {
						const fac_ids = res.resultStr;
						axios({
							method: 'post',
							url: 'https://service.wulings.com/api/code/bindUser',
							data: {
								"openid": this.openid,
								"nick_name": this.userinfo.nickname,
								"fac_ids": fac_ids
							},
							headers: {
								'Content-Type': 'application/x-www-form-urlencoded'
							}
						}).then((res) => {
							if (res.data == 1) {
								console.log("绑定成功！", res);
								showSuccessToast('绑定成功！');
							
							} else {
								console.log("绑定失败！", res);
								showFailToast('绑定失败！');
							}
						}).catch((error) => {
							console.log("绑定失败！", res);
							showFailToast('绑定失败！');
						});
					},
					fail: (err) => {
						// console.log('err', err);
						showFailToast('扫码失败,参数异常');
					}
				});
			},
		}
	}
</script>

<style>

	.bottom-side-otherLogin {
		text-align: center;
		margin-bottom: 50px;
	}

	.main {
		/* background-color: #f7f8fa; */
		height: 100%;
	}

	.flex-container {
		justify-content: space-between;
		flex-direction: column;
	}



	.cell-area-titles {
		flex: 1;
		/* 允许元素根据剩余空间进行分配，实现等宽 */
		justify-content: space-between;
		text-align: center;
		/* 文字居中显示 */
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.text {
		margin-top: 10px;
		margin-bottom: 25px;
		font-size: 36rpx;
	}

	.logo {
		height: 100px;
		width: 100px;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}



	.custom-border {
		border-color: blue;
	}

	.text-area {
		display: flex;
		justify-content: center;
		/* margin-bottom: 25px; */
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>